<script lang="ts" setup>
import { computed, ref, unref } from 'vue'
import { useDrag, useDrop } from 'vue3-dnd'

import { toRefs } from '@vueuse/core'

const props = defineProps<{
  id: any
  index: number
  moveCard: (dragIndex: number, hoverIndex: number) => void
}>()


const card = ref<HTMLDivElement>()
const [, drop] = useDrop({
  accept: 'goods',
  collect(monitor) {
    return {
      handlerId: monitor.getHandlerId(),
    }
  },
  hover(item: any, monitor) {
    if (!card.value) {
      return
    }
    const dragIndex = item.index
    const hoverIndex = props.index
    // Don't replace items with themselves
    if (dragIndex === hoverIndex) {
      return
    }

    // Determine rectangle on screen
    const hoverBoundingRect = card.value?.getBoundingClientRect()

    // Get vertical middle
    const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2

    // Determine mouse position
    const clientOffset:any = monitor.getClientOffset()

    // Get pixels to the top
    const hoverClientY = clientOffset.y - hoverBoundingRect.top

    // Only perform the move when the mouse has crossed half of the items height
    // When dragging downwards, only move when the cursor is below 50%
    // When dragging upwards, only move when the cursor is above 50%

    // Dragging downwards
    if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) {
      return
    }

    // Dragging upwards
    if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) {
      return
    }

    // Time to actually perform the action
    props.moveCard(dragIndex, hoverIndex)

    // Note: we're mutating the monitor item here!
    // Generally it's better to avoid mutations,
    // but it's good here for the sake of performance
    // to avoid expensive index searches.
    item.index = hoverIndex
  },
})

const [collect, drag] = useDrag({
  type: 'goods',
  item: () => {
    return { id: props.id, index: props.index }
  },
  collect: (monitor: any) => ({
    isDragging: monitor.isDragging(),
  }),
})

const { isDragging } = toRefs(collect)
const opacity = computed(() => (unref(isDragging) ? 0 : 1))

const setRef = (el: HTMLDivElement) =>  {
   card.value = drag(drop(el)) as HTMLDivElement
}
</script>

<template>
  <div :ref="setRef" class="card" p-10px my-10px :style="{ opacity }" >
    <slot></slot>
  </div>
</template>

<style lang="less" scoped>
.card {


  background-color: white;
  border: 1px dotted var(--color-neutral-3);
  cursor: move;
}
</style>
